package com.doxiaopu.students.product.service.impl;

import com.doxiaopu.students.component.exception.InsertException;
import com.doxiaopu.students.component.exception.NotMerchantException;
import com.doxiaopu.students.product.entity.GroupSingleRebate;
import com.doxiaopu.students.product.entity.Shuffling;
import com.doxiaopu.students.product.entity.Single;
import com.doxiaopu.students.product.mapper.GroupSingleRebateMapper;
import com.doxiaopu.students.product.mapper.ShufflingMapper;
import com.doxiaopu.students.product.mapper.SingleMapper;
import com.doxiaopu.students.product.service.ISingleService;
import com.doxiaopu.students.product.vo.AdminSingleParameterVO;
import com.doxiaopu.students.product.vo.SingleVO;
import com.doxiaopu.students.product.vo.StatusVO;
import com.doxiaopu.students.user.entity.User;
import com.doxiaopu.students.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Primary
public class SingleServiceImpl implements ISingleService {
    @Autowired
    private SingleMapper singleMapper;
    @Autowired
    private ShufflingMapper shufflingMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GroupSingleRebateMapper groupSingleRebateMapper;


    @Override
    @Transactional
    public void createSinle(SingleVO singleVO,Integer id) throws NotMerchantException {
        User user = userMapper.getById(id);
        if (user.getTypes().equals(1)){
            singleVO.setUserid(user.getTUserId());
            singleVO.setCreatedUser(user.getUsername());
            singleVO.setModifiedUser(user.getUsername());
            Date now = new Date();
            singleVO.setCreatedTime(now);
            singleVO.setModifiedTime(now);
            addSingle(singleVO);
            System.err.println("singleVO:"+singleVO+"======================");
//        给团单头图创建图片
            for (Shuffling shuffling:singleVO.getShufflings()){
                shuffling.setSingleId(singleVO.getFlagid());
                shuffling.setCreatedUser(user.getUsername());
                shuffling.setCreatedTime(now);
                addShufflingImg(shuffling);
            }
            //创建返利表
            GroupSingleRebate groupSingleRebate = new GroupSingleRebate();
            groupSingleRebate.setRebateid(singleVO.getFlagid());
            groupSingleRebate.setRebateAmount(0);
            groupSingleRebate.setCreatedUser(user.getUsername());
            groupSingleRebate.setCreatedTime(now);
            groupSingleRebate.setModifiedUser(user.getUsername());
            groupSingleRebate.setModifiedTime(now);
            addRebate(groupSingleRebate);
        }else {
            throw new NotMerchantException("不是商户，不能创建团单");
        }


    }

    @Override
    public SingleVO getSingle(String flagid) {
        return findSingleById(flagid);
    }


    @Override
    public Map<String, Object> getSingleList(AdminSingleParameterVO adminSingleParameterVO, Integer id ) {
        Integer currentPage = (adminSingleParameterVO.getCurrentPage() - 1) * adminSingleParameterVO.getPageSize();
        adminSingleParameterVO.setCurrentPage(currentPage);
        if(id != null) {
            User user = userMapper.getById(id);
            adminSingleParameterVO.setUserid(user.getTUserId());
        }
        List<SingleVO> SingleList= findSingleList(adminSingleParameterVO);
        for(int i=0;i<SingleList.size();i++){
            SingleVO singleVO = SingleList.get(i);
            singleVO.setGroupSingleRebate(findRebate(SingleList.get(i).getFlagid()));
            SingleList.set(i,singleVO);
        }
        Map<String, Object> res = new HashMap<>();
        Integer total = selectTatal(adminSingleParameterVO);
        res.put("data", SingleList);
        res.put("totle", total);
        return res;
    }

    @Override
    @Transactional
    public void updateSingle(SingleVO singleVO,Integer id) {
        User user = userMapper.getById(id);
        //        把singleVO中的single信息注入到实体类中
        Date now = new Date();
        Single single = new Single();
        single.setTitle(singleVO.getTitle());
        single.setIntroduce(singleVO.getIntroduce());
        single.setPrice(singleVO.getPrice());
        single.setOriginal_price(singleVO.getOriginal_price());
        single.setPackage_name(singleVO.getPackage_name());
        single.setLimit_number(singleVO.getLimit_number());
        single.setPackage_details(singleVO.getPackage_details());
        single.setPurchase_information(singleVO.getPurchase_information());
        single.setGraphic_introduction(singleVO.getGraphic_introduction());
        single.setFlagid(singleVO.getFlagid());
        single.setModifiedUser(user.getUsername());
        single.setModifiedTime(now);
//        修改single类中的信息
        updateSingleById(single);
//        通过setSingleId删除shuffimg所有信息
        for (Shuffling shuffling : singleVO.getShufflings()) {
            shuffling.setSingleId(singleVO.getFlagid());
            deleteShufflingImgBysingle_id(shuffling);
        }
//        循环把singleVO中的shuffingimg信息注入到实体类中.并通过获得的shuffingimg信息创建轮播图
        for (Shuffling shuffling : singleVO.getShufflings()) {
            shuffling.setSingleId(singleVO.getFlagid());
            shuffling.setCreatedUser(user.getUsername());
            shuffling.setCreatedTime(now);
            addShufflingImg(shuffling);
        }
        //修改轮播图信息
//        for (Shuffling shuffling : singleVO.getShufflings()) {
//            shuffling.setSingleId(singleVO.getFlagid());
//            updateInfo(shuffling);
//        }
    }

    @Override
    public Integer updateSale(StatusVO statusVO,Integer id) {
        Integer row = updateSaleStatus(statusVO);
        return row;
    }

    @Override
    @Transactional
    public void updateRebate(StatusVO statusVO, Integer id) {
        User user = userMapper.getById(id);
        Date now = new Date();
        if(statusVO.getRebateState().equals(1)){
            statusVO.setRebateModifiedTime(now);
            GroupSingleRebate groupSingleRebate = new GroupSingleRebate();
            groupSingleRebate.setRebateAmount(statusVO.getRebateAmount());
            groupSingleRebate.setRebateid(statusVO.getFlagid());
            groupSingleRebate.setCreatedUser(user.getUsername());
            groupSingleRebate.setCreatedTime(now);
            groupSingleRebate.setRebateLimit(statusVO.getRebateLimit());
            groupSingleRebate.setTimeId(System.currentTimeMillis());
            Integer Rebaterow = addRebate(groupSingleRebate);
            System.err.print("Rebaterow:"+Rebaterow+"==========");
        }
        statusVO.setModifiedUser(user.getUsername());
        statusVO.setModifiedTime(now);
        Integer RebateStaterow = updateRebateState(statusVO);
        System.err.print("RebateStaterow:"+RebateStaterow+"------------------");
        System.err.print("RebateStaterow:"+statusVO);
    }

    @Override
    public Map<String, Object> getAppSingleList() {
        AdminSingleParameterVO adminSingleParameterVO = new AdminSingleParameterVO();
        Integer currentPage = (adminSingleParameterVO.getCurrentPage() - 1) * adminSingleParameterVO.getPageSize();
        adminSingleParameterVO.setCurrentPage(currentPage);
        Map<String, Object> res = new HashMap<>();
        adminSingleParameterVO.setSaleStatus(1);
        adminSingleParameterVO.setRebateState(1);
        List<SingleVO> SingleList= findSingleList(adminSingleParameterVO);
        for(int i=0;i<SingleList.size();i++){
            SingleVO singleVO = SingleList.get(i);
            singleVO.setGroupSingleRebate(findRebate(SingleList.get(i).getFlagid()));
            SingleList.set(i,singleVO);
        }
        Integer total = selectTatal(adminSingleParameterVO);
        res.put("data", SingleList);
        res.put("totle", total);
        return res;
    }


    /**
     * 加入团单数据
     * @param
     * @return
     */
    private void addSingle(SingleVO singleVO){
        Integer rows = singleMapper.addSingle(singleVO);
        if(rows!=1) {
            throw new InsertException("增加用户数据时出现未知错误");
        }
    };

    /**
     * 插入团单轮播图
     * @param shuffling
     * @return
     */
    private void addShufflingImg(Shuffling shuffling){
        Integer rows = shufflingMapper.addShufflingImg(shuffling);
        if(rows!=1) {
            throw new InsertException("增加用户数据时出现未知错误");
        }
    };

    /**
     * 查询团单列表
     * @return
     * @param adminSingleParameterVO
     */
    List<SingleVO> findSingleList(AdminSingleParameterVO adminSingleParameterVO){
        return singleMapper.findSingleList(adminSingleParameterVO);
    };

    /**
     * 通过setSingleId删除shuffimg
     * @param shuffling
     * @return
     */
    private Integer deleteShufflingImgBysingle_id(Shuffling shuffling) {
        return shufflingMapper.deleteShufflingImgBysingle_id(shuffling);
    };

    /**
     *
     * @param single
     * @return
     */
    private Integer updateSingleById(Single single) {
        System.err.println(single);
        return singleMapper.updateSingleById(single);
    };
    /**
     * 团单列表的总数
     * @param adminSingleParameterVO
     * @return
     */
    private Integer selectTatal(AdminSingleParameterVO adminSingleParameterVO){
        return singleMapper.selectTatal(adminSingleParameterVO);
    };
    /**
     * 创建团单的返利信息
     * @param groupSingleRebate
     * @return
     */
    private Integer addRebate(GroupSingleRebate groupSingleRebate){
        return groupSingleRebateMapper.addRebate(groupSingleRebate);
    };
    /**
     * 通过团单flagid查询团单的详情信息
     * @param flagid
     * @return
     */
    private SingleVO findSingleById(String flagid){
        return singleMapper.findSingleById(flagid);
    };
    /**
     * 修改轮播图
     * @param shuffling
     * @return
     */
    private Integer updateInfo(Shuffling shuffling){
        return shufflingMapper.updateInfo(shuffling);
    };
    /**
     * 更改销售状态
     * @param statusVO
     * @return
     */
    private Integer updateSaleStatus(StatusVO statusVO){
        return singleMapper.updateSaleStatus(statusVO);
    };
    /**
     * 更改返利状态
     * @param statusVO
     * @return
     */
    Integer updateRebateState(StatusVO statusVO) {
        return singleMapper.updateRebateState(statusVO);
    };
    /**
     * 通过rebateid查询返利信息
     * @param rebateid
     * @return
     */
    private GroupSingleRebate findRebate(String rebateid){
        return groupSingleRebateMapper.findRebate(rebateid);
    };
}
